package com.lezijie.seckill.config;

import com.lezijie.seckill.pojo.User;
import com.lezijie.seckill.service.IUserService;
import com.lezijie.seckill.utils.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 孙志鹏
 * @createDate 2021/10/26 21:45
 */
@Component
public class UserArgumentResolvers implements HandlerMethodArgumentResolver {

    @Autowired
    private IUserService userService;

    /**
     * 判断传进来的参数类型(入参)是否是User类型
     * @param methodParameter 传入参数值
     * @return 如果类型匹配则返回true，不匹配则返回false
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        Class<?> clazzParameter = methodParameter.getParameterType();
        return clazzParameter == User.class;
    }

    /**
     * 如果上面的方法返回true，才会执行下面的方法
     * @param methodParameter
     * @param modelAndViewContainer
     * @param nativeWebRequest
     * @param webDataBinderFactory
     * @return
     * @throws Exception 抛出异常
     */
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
        String userTicket = CookieUtil.getCookieValue(request, "userTicket");
        if (!StringUtils.hasLength(userTicket)) {
            return null;
        }
        return userService.getUserByCookie(userTicket,request,response);
    }
}
